package com.woniuxy.woniumall.service;

import com.sun.org.apache.bcel.internal.generic.RET;
import com.woniuxy.woniumall.entity.Book;
import com.woniuxy.woniumall.entity.Cart;
import com.woniuxy.woniumall.entity.User;
import com.woniuxy.woniumall.mapper.BookMapper;
import com.woniuxy.woniumall.mapper.CartMapper;
import com.woniuxy.woniumall.vo.CartVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class CartService {

    @Autowired
    CartMapper cartMapper ;
    @Autowired
    BookMapper bookMapper ;

    public int addCart(int num ,int bookId,int userId){
        try {
            //判断此商品是否被添加过
            Cart cart = cartMapper.isCollected(bookId,userId);
            Book book = bookMapper.selectByPrimaryKey(bookId);

            if (cart != null ) {
                //被添加过
                int newNun = cart.getBuycount() + num;
                double allPrice = cart.getAllprice() + book.getPrice() * num ;
                cart.setAllprice(allPrice);
                cart.setBuycount(newNun);
                //做修改
                cartMapper.updateByPrimaryKey(cart);
            }else {
                //没有被添加过
                Cart newCart = new Cart();
                newCart.setBuycount(num);
                newCart.setAllprice(book.getPrice()*num);
                newCart.setBookId(bookId);
                newCart.setUserId(userId);
                cartMapper.insert(newCart);
            }
            return 1 ;
        }catch (RuntimeException e) {
            throw new RuntimeException();
        }
    }

    public List<CartVo> findMyCart(User user) {
        return cartMapper.selectMyCart(user.getId());
    }

    //@Transactional
    public List<CartVo> modifyMyCart(User user, int bookId, int num) {
        //1. 根据userid ，bookid  查询出一个 cart对象
        //2.查询  book 对象   获取单价
        Book book = bookMapper.selectByPrimaryKey(bookId);
        Cart cart = cartMapper.isCollected(bookId, user.getId());
        //计算 allPrice

        //把新的数量和 小计 设置到cart对象中
        cart.setBuycount(num);
        cart.setAllprice(num*book.getPrice());
        //调用更新方法
        cartMapper.updateByPrimaryKey(cart);
        //查询 List集合  返回
        List<CartVo> list = cartMapper.selectMyCart(user.getId());
        return list;
    }

    public List<CartVo> removeMyCartById(User user, int id) {
        cartMapper.deleteByPrimaryKey(id);
        return cartMapper.selectMyCart(user.getId());
    }

    public List<CartVo> findSubmitCart(User user, Integer[] ids) {
        return cartMapper.selectSubmitCart(user.getId(),ids);
    }
}
